<template>
  <div class="box-content">
    <div class="aside-content">
      <el-container>
        <el-header>
          <div class="card" style="margin-bottom: 5px; margin-top: 20px">
            <el-dropdown>
              <el-button type="primary">
                选择比赛场次<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>上半场</el-dropdown-item>
                  <el-dropdown-item>下半场</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" style="margin-left: 10px" @click="handleImport"
              >导入分数</el-button
            >
            <el-button type="info" style="margin: 0 10px" @click="handleReset">重置</el-button>
          </div>
          <input
            ref="fileInput"
            type="file"
            accept=".xlsx, .xls"
            style="display: none"
            @change="handleFileChange"
          />
        </el-header>
        <el-main>
          <el-table :data="tableData" border stripe style="width: 100%">
            <el-table-column label="排名" prop="rankId" width="70px">
              <template #default="scope">
                <span v-if="scope.row.rankId <= 3" class="ranking-position top-three">{{
                  scope.row.rankId
                }}</span>
                <span v-else class="ranking-position">{{ scope.row.rankId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="选手编号" prop="id"></el-table-column>
            <el-table-column label="选手姓名" prop="name"></el-table-column>
            <el-table-column label="评委1打分" prop="score1">
              <template #default="scope">
                <el-input
                  v-model.number="scores[scope.$index].score1"
                  type="number"
                  placeholder="分数"
                  @input="handleScoreChange(scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column label="评委2打分" prop="score2">
              <template #default="scope">
                <el-input
                  v-model.number="scores[scope.$index].score2"
                  type="number"
                  placeholder="分数"
                  @input="handleScoreChange(scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column label="评委3打分" prop="score3">
              <template #default="scope">
                <el-input
                  v-model.number="scores[scope.$index].score3"
                  type="number"
                  placeholder="分数"
                  @input="handleScoreChange(scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer style="display: flex; justify-content: flex-end">
          <el-button type="primary" @click="handleSave">保存</el-button>
        </el-footer>
      </el-container>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

// 初始数据
const tableData = ref([
  {
    rankId: 1,
    id: '001',
    name: '张三',
    score: 98.5,
    timeOver: '0:00'
  },
  {
    rankId: 2,
    id: '002',
    name: '李四',
    score: 95.0,
    timeOver: '0:25'
  },
  {
    rankId: 3,
    id: '003',
    name: '王五',
    score: 92.0,
    timeOver: '0:40'
  }
])

// 创建一个数组来存储每个选手的三个评委分数
const scores = ref(
  tableData.value.map(() => ({
    score1: null,
    score2: null,
    score3: null
  }))
)

// 计算最终得分
const calculateFinalScore = (index) => {
  const playerScores = scores.value[index]
  const validScores = [playerScores.score1, playerScores.score2, playerScores.score3].filter(
    (score) => score !== null
  )

  if (validScores.length === 0) return 0

  // 计算平均分
  return validScores.reduce((sum, score) => sum + score, 0) / validScores.length
}

// 监听分数变化
const handleScoreChange = (index) => {
  const finalScore = calculateFinalScore(index)
  tableData.value[index].score = finalScore
}

// 添加保存处理函数
const handleSave = () => {
  // 创建包含完整信息的结果数组
  const results = tableData.value.map((player, index) => {
    return {
      rankId: player.rankId,
      id: player.id,
      name: player.name,
      scores: scores.value[index],
      finalScore: player.score
    }
  })

  // 在控制台输出结果
  console.log('评分结果：', results)
  console.log('原始分数数组：', scores.value)

  // 可以添加提示
  ElMessage({
    type: 'success',
    message: '保存成功！'
  })
}

// 处理文件导入
const handleImport = () => {
  // 触发文件选择对话框
  const fileInput = document.querySelector('input[type="file"]')
  fileInput.click()
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (!file) {
    ElMessage({
      type: 'warning',
      message: '请选择一个Excel文件！'
    })
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const importedData = XLSX.utils.sheet_to_json(worksheet)

    // 清空当前数据
    tableData.value = []
    scores.value = []

    // 假设Excel文件格式与初始数据格式一致
    importedData.forEach((item) => {
      tableData.value.push({
        rankId: item.比赛编号,
        id: item.比赛编号,
        name: item.选手姓名,
        score: item.得分,
        timeOver: item.超时
      })
      scores.value.push({
        score1: null,
        score2: null,
        score3: null
      })
    })

    ElMessage({
      type: 'success',
      message: '导入成功！'
    })
  }
  reader.readAsArrayBuffer(file)
  console.log(tableData.value)
}

// 重置数据
const handleReset = () => {
  tableData.value = []
  scores.value = tableData.value.map(() => ({
    score1: null,
    score2: null,
    score3: null
  }))
}
</script>

<style>
.box-content {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;

  height: 100%;
  width: 100%;
}

.aside-content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  margin: 0 15px;
  height: 90%;
  width: 90%;
  border-radius: 10px;
  box-shadow: 2px 2px 5px #888888;
  background-color: white;
}

.ranking-position {
  font-weight: bold;
}

.top-three {
  color: red;
}
</style>
